package com.dq.mybatis.core;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.XPath;
import org.dom4j.io.SAXReader;

/*读取并解析配置文件mybatis-config.xml
 * @author dq
 * @date 2020年2月21 日
 */
public class MyBatisConfig {
	//存放数据库连接的信息
	private Map<String, String> dataSourceMap = new HashMap<String, String>();
	
	// mapper映射文件的路径
	private List<String> mappers = new ArrayList<String>();
	
	public MyBatisConfig(String config) {
		readXml(config); //读取这个配置文件
	}
	
	/*读取配置文件的方法
	 * @param config
	 */
	@SuppressWarnings("unchecked")
	private void readXml(String config) {
		SAXReader read = new SAXReader();
		try (InputStream is = this.getClass().getClassLoader().getResourceAsStream(config)) {
			Document doc = read.read(is); //将这个文档流转成Document对象，文档树
			//从doc中使用迎快速查找 property
			XPath xpath = doc.createXPath("//dataSource/property");
			//查找 _
			List<Element> list = xpath.selectNodes(doc); // 从doc中查找满足条件的节点
			for (Element el : list) {
				dataSourceMap.put(el.attributeValue("name"), el.attributeValue("value"));
			}
			xpath = doc.createXPath("//mappers/mapper"); //获取所有文件的路径
			List<Element> mps = xpath.selectNodes(doc);
			for (Element el : mps) {
				mappers. add (el. attributeValue("resource")); //取mapper节点的 resource属性的属性值
			}
			System.out.println(mappers);
		} catch (IOException e) {
			e.printStackTrace();
		} catch (DocumentException e) {
			e.printStackTrace();
		}
	}

	public Map<String, String> getDataSourceMap() {
		return this.dataSourceMap;
	}
	public List<String> getMappers(){
		return mappers;
	}
}